package com.qcby.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qcby.common.exception.BusinessException;
import com.qcby.entity.TProductCategory;
import com.qcby.form.TProductCategoryForm;
import com.qcby.form.TProductCategoryListForm;
import com.qcby.mapper.TProductCategoryMapper;
import com.qcby.mapper.TProductMapper;
import com.qcby.service.TProductCategoryService;
import com.qcby.vo.PageVO;
import com.qcby.vo.TProductCategoryVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class TProductCategoryServiceImpl extends ServiceImpl<TProductCategoryMapper, TProductCategory> implements TProductCategoryService {

    @Autowired
    private TProductCategoryMapper categoryMapper;
    
    @Autowired
    private TProductMapper productMapper;

    @Override
    public PageVO<TProductCategoryVO> getCategoryList(TProductCategoryListForm form) {
        Page<TProductCategory> page = new Page<>(form.getPage(), form.getLimit());
        
        QueryWrapper<TProductCategory> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StringUtils.hasText(form.getCategoryName()), "category_name", form.getCategoryName())
                .eq("is_deleted", 0)
                .orderByAsc("sort");
                
        Page<TProductCategory> resultPage = categoryMapper.selectPage(page, queryWrapper);
        
        List<TProductCategoryVO> voList = new ArrayList<>();
        for (TProductCategory category : resultPage.getRecords()) {
            TProductCategoryVO vo = convertToVO(category);
            // 查询分类下的商品数量
            Integer count = productMapper.selectCount(new QueryWrapper<>()
                    .eq("category_id", category.getCategoryId())
                    .eq("is_deleted", 0));
            vo.setProductCount(count);
            voList.add(vo);
        }
        
        return new PageVO<>(voList, resultPage.getTotal(), form.getPage(), form.getLimit());
    }

    @Override
    @Transactional
    public void addCategory(TProductCategoryForm form) {
        // 检查分类名称是否重复
        if (checkCategoryNameExists(form.getCategoryName(), null)) {
            throw new BusinessException("分类名称已存在");
        }
        
        TProductCategory category = new TProductCategory();
        BeanUtils.copyProperties(form, category);
        
        category.setCreateTime(LocalDateTime.now());
        category.setUpdateTime(LocalDateTime.now());
        category.setIsDeleted(0);
        
        categoryMapper.insert(category);
    }

    @Override
    @Transactional
    public void updateCategory(Integer id, TProductCategoryForm form) {
        TProductCategory category = checkCategoryExists(id);
        
        // 检查分类名称是否重复
        if (checkCategoryNameExists(form.getCategoryName(), id)) {
            throw new BusinessException("分类名称已存在");
        }
        
        BeanUtils.copyProperties(form, category);
        category.setUpdateTime(LocalDateTime.now());
        
        categoryMapper.updateById(category);
    }

    @Override
    @Transactional
    public void deleteCategory(Integer id) {
        TProductCategory category = checkCategoryExists(id);
        
        // 检查分类下是否有商品
        Integer count = productMapper.selectCount(new QueryWrapper<>()
                .eq("category_id", id)
                .eq("is_deleted", 0));
        if (count > 0) {
            throw new BusinessException("该分类下还有商品，不能删除");
        }
        
        category.setIsDeleted(1);
        category.setUpdateTime(LocalDateTime.now());
        
        categoryMapper.updateById(category);
    }

    private TProductCategory checkCategoryExists(Integer id) {
        TProductCategory category = categoryMapper.selectById(id);
        if (category == null || category.getIsDeleted() == 1) {
            throw new BusinessException("商品分类不存在");
        }
        return category;
    }

    private boolean checkCategoryNameExists(String categoryName, Integer excludeId) {
        QueryWrapper<TProductCategory> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("category_name", categoryName)
                .eq("is_deleted", 0);
        if (excludeId != null) {
            queryWrapper.ne("category_id", excludeId);
        }
        return categoryMapper.selectCount(queryWrapper) > 0;
    }

    private TProductCategoryVO convertToVO(TProductCategory category) {
        TProductCategoryVO vo = new TProductCategoryVO();
        BeanUtils.copyProperties(category, vo);
        return vo;
    }
} 